# -*- coding: utf-8 -*-

# This code shows an example of text translation from English to Simplified-Chinese.
# This code runs on Python 2.7.x and Python 3.x.
# You may install `requests` to run this code: pip install requests
# Please refer to `https://api.fanyi.baidu.com/doc/21` for complete api document

import json
import random
from hashlib import md5

import requests

# Set your own appid/appkey.
appid = '20250715002407008'
appkey = 'xD5jLaqbGESuy00oWo28'

endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path


# Generate salt and sign
def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()


def translate(from_lang: str, to_lang: str, query):
    salt = random.randint(32768, 65536)
    sign = make_md5(appid + query + str(salt) + appkey)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
    r = requests.post(url, params=payload, headers=headers)
    rs =  r.json()
    trans_result = rs.get('trans_result')
    rs = trans_result[0].get('dst')
    # print(type(rs))
    return rs


if __name__ == '__main__':
    # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
    # 自动检测auto 英语en 泰语th 越南语vie 中文zh
    from_lang = 'en'
    to_lang = 'zh'
    query = 'Hello World! This is 1st paragraph.\nThis is 2nd paragraph.'
    result = translate(from_lang, to_lang, query)

    # Show response
    print(json.dumps(result, indent=4, ensure_ascii=False))
